package com.ciwong.epaper.modules.epaper.ui;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.TrafficStats;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.CatelogBean;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.Node;
import com.ciwong.epaper.modules.epaper.bean.PackageInfo;
import com.ciwong.epaper.modules.epaper.bean.Video;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.HomeWorkUtil;
import com.ciwong.epaper.modules.epaper.util.LayersView;
import com.ciwong.epaper.modules.epaper.util.ScrollViewExtend;
import com.ciwong.epaper.modules.epaper.util.ViewPageTitle;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.DoubleClickCheckUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.GlideRoundTransform;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoad;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilelib.widget.DownloadProgressBar;
import com.ciwong.mobilelib.widget.TitleBar;
import com.jude.rollviewpager.adapter.StaticPagerAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 书籍详情
 * Created by dylan on 2016/11/23.
 */
public class CatalogNewActivity extends BaseActivity implements ScrollViewExtend.ScrollViewListener, View.OnClickListener, ViewPageTitle.ViewPageChanag {
    private LayoutInflater mInflater;
    private List<String> pageTitles;
    private ViewPager viewpager_catalog;


    private ScrollViewExtend mScrollView;

    private int mSubjectId = -1;


    @Override
    protected int setView() {
        return R.layout.catalog_new;
    }

    //控件
    private TitleBar titleBar;
    private TextView bookTitle, mTvGrade, mTvWatches, mTvAddBookToBookDesk;
    private TextView bookDescription;
    private RelativeLayout mRlVideoIntro;
    private ImageView bookCovImage, mIvKaoShi, mIvFree, mIvVideoIntro;


    //添加书本
    private Button btnAddBook;


    //----------------------业务相关
    private EpaperInfo mInfo;
    private String mBookId;
    private int fromResource;// 来源

    //--------------返回数据
    private CatelogBean catelogBean;
    private Video video;
    private List<Node> dataPack = new ArrayList<>();


    //获取通过Mobile连接收到的字节总数
    private long total_data = TrafficStats.getTotalRxBytes();

    /**
     * 扫一扫数据所属的服务列表
     */
    private List<EpaperInfo.Server> mEpaperServerList;

    /**
     * 服务ID
     */
    private int mServiceId;

    //错误提示信息
    private Object mesData;


    /**
     * 传给AddBookActivity的标识
     */
    public static final String CLOSE_ADDBOOKACTIVITY = "CLOSE_ADDBOOKACTIVITY";


    private List<CatalogueInfo> mCatalogueInfos = new ArrayList<>();
    private List<DownLoadInfo> mDownLoadInfos = new ArrayList<>();


    private Handler mHandler = new Handler();
    private Map<DownLoadInfo, Hoder> downLoadInfoMap = new HashMap<DownLoadInfo, Hoder>();
    private ArrayList<String> bookchapters = new ArrayList<String>();

    private LayersView contentLayersView;

    public static final int ACTION_ADD_BOOK_TO_BOOKDESK = 0;
    public static final int ACTION_REOMVEBOOK_TO_BOOKDESK = 1;
    private int currentActionOfAddBookButton;

    @Override
    protected void findViews() {

        try {

            btnAddBook = (Button) findViewById(R.id.tv_add_book_to_bookcase);
            //mTvAddBookToBookDesk = (TextView) findViewById(R.id.tv_add_to_bookdesk);
            titleBar = (TitleBar) findViewById(R.id.activity_base_titlebar);
            titleBar.setTitle("书籍详情");
            mScrollView = (ScrollViewExtend) findViewById(R.id.scro_mian);
            bookTitle = (TextView) findViewById(R.id.book_title);
            bookCovImage = (ImageView) findViewById(R.id.book_cov);
            mTvGrade = (TextView) findViewById(R.id.tv_grade);
            bookDescription = (TextView) findViewById(R.id.tv_watches);
            mIvKaoShi = (ImageView) findViewById(R.id.img_kaoshi);
            mIvFree = (ImageView) findViewById(R.id.img_free);
            mIvVideoIntro = (ImageView) findViewById(R.id.iv_video_intro);


            mRlVideoIntro = findViewById(R.id.rl_video_intro);
            viewpager_catalog = (ViewPager) findViewById(R.id.viewpager_catalog);

            //setAddBookTextViewText();

        } catch (NullPointerException e) {
            e.getStackTrace();
        }


    }

    private void setAddBookTextViewText() {
        if (currentActionOfAddBookButton == ACTION_REOMVEBOOK_TO_BOOKDESK) {
            mTvAddBookToBookDesk.setText(getResources().getString(R.string.remove_bookcase));
        } else {
            mTvAddBookToBookDesk.setText(getResources().getString(R.string.add_bookcase));
        }
    }

    @Override
    protected void loadData() {
        //先加载本地数据
        getLocData();

        if (mInfo.getRequired() == 1) {
            getLocKaoShi();
        }


    }

    /**
     * 获取本地的考试用书
     */
    private void getLocKaoShi() {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_KAOSHI + mBookId, new BaseCallBack() {


                    @Override
                    public void success(Object data) {
                        if (data != null) {
                            bookchapters.clear();
                            bookchapters = (ArrayList<String>) data;
                            if (contentLayersView != null) {
                                contentLayersView.setBookchapters(bookchapters);
                                contentLayersView.bindLinearLayout();
                            }
                            //网络获取
                            getKaoShi();
                        }
                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        getKaoShi();
                    }

                    @Override
                    public void failed(Object data) {
                        getKaoShi();
                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

    }

    /**
     * 判断网络数据跟本地数据是否有变化如果没有则不需要刷新
     *
     * @return
     */
    private boolean refBookchap(Object data) {
        if (bookchapters == null) {
            //如果等于null肯定要更新数据刷新的
            return true;
        }
        ArrayList<String> tempList = (ArrayList<String>) data;
        if (tempList.size() != bookchapters.size()) {
            //如果大小不相等了那数据发生变化了更新
            return true;
        }
        for (int i = 0; i < tempList.size(); i++) {
            if (!tempList.get(i).equals(bookchapters.get(i))) {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取解锁后的章节
     */
    private void getKaoShi() {
        EpaperDao.getInstance().getReceiveBookchapters(EApplication.BRAND_ID, mServiceId, mBookId, new BaseExtCallBack(CatalogNewActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void success(Object data) {
                if (data != null) {
                    if (refBookchap(data)) {
                        bookchapters.clear();
                        bookchapters = (ArrayList<String>) data;
                        if (contentLayersView != null) {
                            contentLayersView.setBookchapters(bookchapters);
                            contentLayersView.bindLinearLayout();
                        }
                        //缓存数据本地数据无网络也可以操作
                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_KAOSHI + mBookId, bookchapters);
                    }
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                super.failed(data);
            }
        });
    }


    /**
     * 获取本地数据
     */
    private void getLocData() {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {
                SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_CATALOGUE + mBookId, new BaseCallBack() {
                    @Override
                    public void failed(int errorCode, Object data) {
                        //                        DialogUtil.showFailedToastByErrorType(CatalogNewActivity.this,mesData);
                        //                        toError();
                        showLoadingView();
                        loadNetData();
                    }

                    @Override
                    public void failed(Object data) {
                        //                        DialogUtil.showFailedToastByErrorType(CatalogNewActivity.this,mesData);
                        //                        toError();
                        showLoadingView();
                        loadNetData();
                    }

                    @Override
                    public void success(Object data) {
                        try {
                            if (data != null) {
                                //获取本地DownLoadInfos

                                //获取缓存数据
                                if (data instanceof CatelogBean) {
                                    catelogBean = (CatelogBean) data;
                                    if (catelogBean != null) {
                                        if (catelogBean != null) {
                                            mCatalogueInfos.clear();
                                            mCatalogueInfos = catelogBean.getCatalogues();
                                        }
                                        mInfo.setCover(catelogBean.getPackages().getCover());
                                        mInfo.setPeriodName(catelogBean.getPackages().getBook_name());
                                        mInfo.setPeriod(catelogBean.getPackages().getPeriodId());
                                        mDownLoadInfos = DownLoadDB.queryListByBookId(mBookId, CatalogueInfo.PackageMode.PACKAGE_MODE_OLD);

                                        if (mDownLoadInfos.size() == 0 || mDownLoadInfos == null) {
                                            //如果数据库没有数据得先添加到数据库
                                            Log.d("DownLoadInfos", "####mDownLoadInfos.size() == 0 || mDownLoadInfos == null#########");
                                            mDownLoadInfos = fillList(mCatalogueInfos);
                                        } else {
                                            Log.d("DownLoadInfos", "####mDownLoadInfos.size()#########" + mDownLoadInfos.size());
                                        }
                                        upData();
                                    } else {
                                        //                                    toError();
                                    }
                                } else {
                                    //                                toError();
                                }
                            }
                            loadNetData();
                        } catch (Exception e) {
                            e.getStackTrace();
                        }

                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }


    /**
     * 更新数据
     */
    private void upData() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hideCricleProgress();


                //                bookTitle.setText(catelogBean.getPackages().getBook_name());
                //                bookTitle.setText(mInfo.getProductName());

                if (catelogBean.getPackages() != null) {
                    if (catelogBean.getPackages().getWatchs() != null && !catelogBean.getPackages().getWatchs().equals("")) {
                        bookDescription.setText(catelogBean.getPackages().getWatchs());
                    }
                    video = catelogBean.getPackages().getVideo();
                    if (video != null && !TextUtils.isEmpty(video.getVideo_unique())) {
                        mRlVideoIntro.setVisibility(View.VISIBLE);
                    } else {
                        mRlVideoIntro.setVisibility(View.GONE);
                    }

                    if (!TextUtils.isEmpty(catelogBean.getPackages().getGradeId())) {
                        String grade = EConstants.GRADE_DATA.get(Integer.parseInt(catelogBean.getPackages().getGradeId()));
                        if (!TextUtils.isEmpty(grade)) {
                            mTvGrade.setText("适用于:  " + grade);
                        } else {
                            mTvGrade.setText("适用于:  无 ");
                        }

                    }

                }

                mIvKaoShi.setVisibility(mInfo.getRequired() == 1 ? View.VISIBLE : View.INVISIBLE);
                mIvFree.setVisibility(mInfo.getIsFree() == 1 ? View.VISIBLE : View.INVISIBLE);


                if (catelogBean != null) {
                    dataPack.clear();
                    for (int i = 0; i < catelogBean.getPackages().getPackageinfo().size(); i++) {
                        dataPack.add(new Node(i + 1, 0, null, catelogBean.getPackages().getPackageinfo().get(i)));
                    }
                    //所属服务本地取
                    if (fromResource == IntentValue.JumpToBookCatalogType.FROM_SCAN) {
                        //扫描二维码
                        if (mEpaperServerList != null) {
                            StringBuffer sbSer = new StringBuffer();
                            for (int i = 0; i < mEpaperServerList.size(); i++) {
                                if (i == (mEpaperServerList.size() - 1)) {
                                    sbSer.append(mEpaperServerList.get(i).getName());
                                } else {
                                    sbSer.append(mEpaperServerList.get(i).getName() + ",");
                                }
                            }
                            dataPack.add(new Node(-1, 0, null, new PackageInfo(0, 0, "所属服务", sbSer.toString())));
                        }
                    } else {
                        if (mInfo != null && mInfo.getServer() != null) {
                            dataPack.add(new Node(-1, 0, null, new PackageInfo(0, 0, "所属服务", mInfo.getServer().getName())));
                        }
                    }

                }
                initViewPage();
                try {

                    bookCovImage.setVisibility(View.VISIBLE);
                    try {
                        if (!isFinishing()) {
                            if (CatalogNewActivity.this != null) {
                                String newUri = mInfo.getCover() + "?x-oss-process=image/resize,w_200,m_mfit/quality,Q_60";
                                Glide.with(CatalogNewActivity.this).load(newUri).transform(new CenterCrop(CatalogNewActivity.this), new GlideRoundTransform(CatalogNewActivity.this, 6)).into(bookCovImage);
                            }
                        }
                    } catch (Exception e) {

                    }
                } catch (Exception e) {
                    e.getStackTrace();
                }

            }
        });


        //
    }


    private void loadNetData() {

        EpaperDao.getInstance().getBookCatalogue(mBookId, "", null, new BaseExtCallBack(CatalogNewActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


            @Override
            public void success(final Object data) {
                hidenLoadingView();
                try {
                    //后台没数据临时用之前的接口
                    catelogBean = (CatelogBean) data;
                    if (catelogBean != null) {
                        mCatalogueInfos.clear();
                        mCatalogueInfos = catelogBean.getCatalogues();
                        mSubjectId = catelogBean.getPackages().getSubjectId();

                        mInfo.setCover(catelogBean.getPackages().getCover());
                        mInfo.setPeriodName(catelogBean.getPackages().getBook_name());
                        mInfo.setPeriod(catelogBean.getPackages().getPeriodId());
                    }
                    //缓存数据本地数据无网络也可以操作
                    SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_BOOK_CATALOGUE + mBookId, catelogBean);

                    //先获取之前存的数据库信息已避免已经存在的数据库状态被清空
                    mDownLoadInfos = DownLoadDB.queryListByBookId(mBookId, CatalogueInfo.PackageMode.PACKAGE_MODE_OLD);
                    //如果数据库没有数据得先添加到数据库
                    mDownLoadInfos = fillList(mCatalogueInfos);
                    upData();
                } catch (Exception e) {
                    e.getStackTrace();
                }

            }

            @Override
            public void failed(int errorCode, Object data) {
                hidenLoadingView();
                hideMiddleProgressBar();
                //网络获取失败了再走本地获取流程
                super.failed(errorCode, data);
                mesData = data;
                toError();
            }

            @Override
            public void failed(Object data) {
                hidenLoadingView();
                //                        getLocData();
                hideMiddleProgressBar();
                super.failed(data);
                mesData = data;
                toError();
            }
        });
    }

    private void toError() {
        //        hideCricleProgress();
        if (catelogBean == null) {
            DialogUtil.showFailedToastByErrorType(CatalogNewActivity.this, mesData);
            showErrorMessage(false);
        }
    }


    private void showErrorMessage(boolean isKaoShi) {
        findViewById(R.id.load_err).setVisibility(View.VISIBLE);
        findViewById(R.id.mian_rel).setVisibility(View.GONE);
        titleBar.setVisibility(View.VISIBLE);
        titleBar.setTitle(mInfo.getProductName());
        if (isKaoShi) {
            ((ImageView) findViewById(R.id.error_image)).setImageResource(R.mipmap.no_erweima);
        }
    }


    @Override
    protected void preCreate() {
        mInfo = (EpaperInfo) getIntent().getSerializableExtra(BaseIntentFlag.INTENT_FLAG_OBJ);
        fromResource = getIntent().getIntExtra(BaseIntentFlag.INTENT_FLAG_ACTION, IntentValue.JumpToBookCatalogType.NORMAL);
        //服务器没有数据所以先用死的
        if (mInfo != null) {
            if (!TextUtils.isEmpty(mInfo.getPackageId())) {
                mBookId = mInfo.getPackageId();
                //                            mBookId = "2760";
                mInfo.setPackageId(mBookId);
            } else {
                mBookId = mInfo.getProductId();
                //                            mBookId = "2760";
                mInfo.setPackageId(mBookId);
            }

        }
        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
        mEpaperServerList = (List<EpaperInfo.Server>) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ_LIST);

        List<EpaperInfo> bookDeskEpaperInfos = EApplication.getInstance().getBookDeskEpaperInfos();
        if (bookDeskEpaperInfos != null && bookDeskEpaperInfos.size() > 0) {
            for (int i = 0; i < bookDeskEpaperInfos.size(); i++) {
                EpaperInfo epaperInfo = bookDeskEpaperInfos.get(i);
                if (epaperInfo != null && mServiceId == epaperInfo.getServerId() && !TextUtils.isEmpty(epaperInfo.productId) && epaperInfo.productId.equals(mBookId)) {
                    currentActionOfAddBookButton = ACTION_REOMVEBOOK_TO_BOOKDESK;
                }
            }
        }
    }

    /**
     * 判断是否是考试用书
     *
     * @return
     */
    private boolean isKaoshi() {
        if (mEpaperServerList == null || mEpaperServerList.size() == 0) {
            return false;
        }
        for (int i = 0; i < mEpaperServerList.size(); i++) {
            if (mEpaperServerList.get(i).getRequired() == 1) {
                return true;
            }
        }
        return false;
    }


    @Override
    protected void init() {
        //        TAG = "LayersView";

        mInflater = LayoutInflater.from(this);
        //        mScrollView.setScrollViewListener(this);
        bookTitle.setText(mInfo.getProductName());


        if (mInfo.isBookCase == 1 || fromResource == IntentValue.JumpToBookCatalogType.FROM_DESK_BOOK || fromResource == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs) {//如果已经添加到了书桌，则将添加到书桌按钮灰色
            btnAddBook.setVisibility(View.GONE);
        } else {
            btnAddBook.setBackgroundResource(R.drawable.button_light_green_selector);
            btnAddBook.setText("添加到书桌");
            btnAddBook.setVisibility(View.GONE);
        }

        /*if (from == IntentValue.JumpToBookCatalogType.FROM_DESK_BOOK || from == IntentValue.JumpToBookCatalogType.FROM_SEARCH_BOOK || from == IntentValue.JumpToBookCatalogType.FROM_ADD_BOOK) {
            mTvAddBookToBookDesk.setVisibility(View.VISIBLE);
        } else {
            mTvAddBookToBookDesk.setVisibility(View.GONE);
        }*/

        if (isKaoshi()) {
            showErrorMessage(true);
        }

    }


    private void initViewPage() {
        pageTitles = new ArrayList<String>();
        pageTitles.add("内容目录");
        viewpager_catalog.setAdapter(new ViewPageTest(pageTitles, mDownLoadInfos));


    }

    @Override
    protected void initEvent() {
        //添加书籍
        //        btnAddBook.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View v) {
        //                if (mInfo.isBookCase == 1) {//已经被添加到了书桌。
        //                    return;
        //                }
        //                if (NetworkUtils.isOnline()) {
        //                    setBookcaseToServer();
        //                    // Toast.makeText(CatalogActivity.this, "111成功添加到书桌！", Toast.LENGTH_SHORT).show();
        //                } else {
        //                    showErrorDialog();
        //
        //                }
        //            }
        //        });
        setDownloadProgressOnDismissListener(new DownloadProgressBar.OnDownLoadDialogDismissListener() {
            @Override
            public void ondDismiss(DownloadProgressBar downloadProgressBar) {
                int status = mCurrentDownloadInfo.getStatus();
                if (status == DownloadStatus.STATUS_LOADING || status == DownloadStatus.STATUS_DOWNLOADING) {
                    DownLoad.getInstance().pauseTask(mCurrentDownloadInfo);
                }
            }
        });
        mIvVideoIntro.setOnClickListener(this);
        /*mTvAddBookToBookDesk.setOnClickListener(this);*/
    }


    public void onEventMainThread(EventBusFactory.DownloadEvent item) {
        DownLoadInfo info = item.getInfo();
        Hoder hoder = findHoder(info);
        mCurrentDownloadInfo = info;
        mCurrentHolder = hoder;
        dealCircleProgress(info, hoder);
    }

    private Hoder findHoder(DownLoadInfo info) {
        for (DownLoadInfo key : downLoadInfoMap.keySet()) {
            if (key.getChapterId().equals(info.getChapterId()) && key.getChapterName().equals(info.getChapterName())) {
                debug("----------keykey-------------" + key.getChapterId() + "-----固定的info------" + info.getChapterId() + "---------name--" + key.getChapterName() + "----" + info.getChapterName());
                return downLoadInfoMap.get(key);
            }
        }
        return null;
    }


    @Override
    public void onScrollChanged(int x, int y, int oldx, int oldy) {
        //通过标题的y坐标来判断
        //        if (y >= (page_titles.getY() - topLin.getHeight())) {
        //            mViewPageTitleXiFu.setVisibility(View.VISIBLE);
        //            backIma.setImageResource(R.mipmap.back_book);
        //            topLin.setBackgroundColor(this.getResources().getColor(R.color.green));
        //            titleText.setVisibility(View.VISIBLE);
        //            page_titles.setVisibility(View.INVISIBLE);
        //            Log.e(TAG, "onScrollChanged: mViewPageTitleXiFu VISIBLE" );
        //        } else {
        //            topLin.setBackgroundColor(this.getResources().getColor(R.color.transparent));
        //            backIma.setImageResource(R.mipmap.v_back);
        //            page_titles.setVisibility(View.VISIBLE);
        //            mViewPageTitleXiFu.setVisibility(View.INVISIBLE);
        //            titleText.setVisibility(View.INVISIBLE);
        //            Log.e(TAG, "onScrollChanged: mViewPageTitleXiFu INVISIBLE" );
        //        }
    }


    /**
     * 执行数据库线程操作  从数据库中获取下载对象
     */
    public void executorDBThread(final CatalogueInfo catalogueInfo, final Hoder hoder) {
        ThreadTask.getInstance().executorDBThread(new Runnable() {
            @Override
            public void run() {

                final DownLoadInfo downLoadInfo = getLocalDownLoadInfoByDB(catalogueInfo);
                mCurrentClickDownloadInfo = downLoadInfo;
                if (downLoadInfo != null) {
                    CWLog.e(TAG, "run: doClickListener" + downLoadInfo.getChapterName());
                }

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        doClickListener(catalogueInfo, downLoadInfo, hoder, true);
                    }
                });

            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /**
     * 获取数据库中DownLoadInfos
     *
     * @param curInfo
     */
    private DownLoadInfo getLocalDownLoadInfoByDB(CatalogueInfo curInfo) {
        List<DownLoadInfo> tempList = DownLoadDB.queryListByBookId(mBookId, CatalogueInfo.PackageMode.PACKAGE_MODE_OLD);
        DownLoadInfo downLoadInfo = null;


        for (DownLoadInfo info : tempList) {
            if (info.getChapterId().equals(curInfo.getId())) {
                downLoadInfo = info;
            }
        }
        if (downLoadInfo != null) {
            return downLoadInfo;
        } else {
            return null;
        }

    }


    /**
     * item监听事件
     *
     * @param downLoadInfo
     */
    public void doClickListener(final CatalogueInfo catalogueInfo, final DownLoadInfo downLoadInfo, Hoder hoder, boolean isHandClick) {
        if (fromResource == IntentValue.JumpToBookCatalogType.NORMAL || fromResource == IntentValue.JumpToBookCatalogType.FROM_ADD_BOOK
                || fromResource == IntentValue.JumpToBookCatalogType.FROM_SCAN || fromResource == IntentValue.JumpToBookCatalogType.FROM_SEARCH_BOOK
                || fromResource == IntentValue.JumpToBookCatalogType.FROM_DESK_BOOK || fromResource == IntentValue.JumpToBookCatalogType.FROM_NEW_DESK_BOOK
                || fromResource == IntentValue.JumpToBookCatalogType.FROM_RESOURCE_CENTER_DICTATION) {

            if (catalogueInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW)
            //            if (catalogueInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_OLD)
            {
                //新结构此处不需要下载
                EpaperJumpManager.jumpToContentNew(R.string.go_back, CatalogNewActivity.this, catalogueInfo, mServiceId, mInfo, mEpaperServerList, fromResource);

            } else if (downLoadInfo != null) {
                if (TextUtils.isEmpty(downLoadInfo.getUrl())) {
                    showToastError(R.string.package_no_publish);
                    return;
                }
                downLoadInfoMap.put(downLoadInfo, hoder);
                switch (downLoadInfo.getStatus()) {
                    case DownloadStatus.STATUS_NORMAL:
                    case DownloadStatus.STATUS_FAILED:
                    case DownloadStatus.STATUS_FAILED_SDISFULL:
                    case DownloadStatus.STATUS_FAILED_UNZIP:
                        if (DialogUtil.sdIsFullForDownload(CatalogNewActivity.this, downLoadInfo)) {
                            DialogUtil.showSdFullDialog(CatalogNewActivity.this, downLoadInfo.getSize());
                            return;
                        }

                        downLoadInfo.setHash(catalogueInfo.getHash());//只有下载的时候更新HASH值
                        judgeDownloadMetod(catalogueInfo, downLoadInfo, hoder);
                        break;
                    case DownloadStatus.STATUS_LOADING:
                        DownLoad.getInstance().pauseTask(downLoadInfo);
                        break;
                    case DownloadStatus.STATUS_DOWNLOADING:
                        DownLoad.getInstance().pauseTask(downLoadInfo);
                        break;
                    case DownloadStatus.STATUS_PAUSE:
                        if (NetworkUtils.isOnline()) {
                            if (NetworkUtils.isWifiOnline()) {
                                showDownloadDialog(downLoadInfo, catalogueInfo, hoder);
                                DownLoad.getInstance().resumeTask(downLoadInfo);
                            } else {
                                DialogUtil.showWIFIDialogOfCatalog(CatalogNewActivity.this, downLoadInfo, catalogueInfo, hoder);
                            }
                        } else {
                            ToastUtil.INSTANCE.toastCenterNoNetError();
                        }
                        break;
                    case DownloadStatus.STATUS_UPZIPING:
                        // DownLoad.getInstance().addTask(info);
                        break;
                    case DownloadStatus.STATUS_COMPLETED:
                        //判断是否需要更新离线包
                        if (null != downLoadInfo.getHash() && !(downLoadInfo.getHash().equals(catalogueInfo.getHash()))) {//资源包有更新
                            reDownloadOrOnlyDeleteData(catalogueInfo, downLoadInfo, hoder, isHandClick);
                        } else {
                            String packageDir = ESystem.getPackagesMainJsonPath(downLoadInfo.getBookId(), downLoadInfo.getChapterId());

                            //新包拆分逻辑增加 资源 versionId,
                            String catalogueJsonPath = ESystem.getPackagesCatalogueJsonPath(downLoadInfo.getBookId(), downLoadInfo.getChapterId());
                            String resourcePath = ESystem.getPackagesResourcePath(downLoadInfo.getBookId(), downLoadInfo.getChapterId());
                            //服务权限判断，跳转资源详情页
                            if (new File(packageDir).exists() && new File(catalogueJsonPath).exists() && new File(resourcePath).exists() && new File(resourcePath).list().length > 0) {//lzh添加此处保证资源存在
                                //自动打开才去判断
                                if (!isHandClick) {
                                    if (!HomeWorkUtil.isDownloadInfoTheSameToClickDownLoadInfo(downLoadInfo, mCurrentClickDownloadInfo)) {
                                        return;
                                    }
                                }
                                EpaperJumpManager.jumpToContent(R.string.go_back, CatalogNewActivity.this, downLoadInfo, mServiceId, mInfo, mEpaperServerList);
                            } else {
                                reDownloadOrOnlyDeleteData(catalogueInfo, downLoadInfo, hoder, isHandClick);
                            }

                        }
                        break;
                }
            }


        } else {//来自资源中心点击了资源包，不允许下载和使用。

        }
    }

    private void reDownloadOrOnlyDeleteData(CatalogueInfo catalogueInfo, final DownLoadInfo downLoadInfo, Hoder hoder, boolean isHandClick) {
        String path = ESystem.getPackagesCatalogue(downLoadInfo.getBookId(), downLoadInfo.getChapterId());//资源包地址
        //删除本地文件
        FileUtils.delete(path);
        //重新下载
        downLoadInfo.setHash(catalogueInfo.getHash());//只有下载的时候更新HASH值
        downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
        downLoadInfo.setProgress(0);
        if (isHandClick) {
            downLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
            judgeDownloadMetod(catalogueInfo, downLoadInfo, hoder);
        } else {
            ThreadTask.getInstance().executorDBThread(new Runnable() {
                public void run() {
                    DownLoadDB.insertDetail(downLoadInfo);
                }
            }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
            ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);

        }
    }

    private void judgeDownloadMetod(CatalogueInfo catalogueInfo, DownLoadInfo downLoadInfo, Hoder hoder) {
        if (NetworkUtils.isOnline()) {
            if (NetworkUtils.isWifiOnline()) {
                showDownloadDialog(downLoadInfo, catalogueInfo, hoder);
                DownLoad.getInstance().addTask(downLoadInfo);
            } else {
                DialogUtil.showWIFIDialogOfCatalog(CatalogNewActivity.this, downLoadInfo, catalogueInfo, hoder);
            }
        } else {
            ToastUtil.INSTANCE.toastCenterNoNetError();
        }

    }


    /**
     * 从网络下载的数据catalogueInfos，递归获取小题和子题，放至downLoadInfos中
     *
     * @param downLoadInfos
     * @param catalogueInfos
     */
    private void parseCatalogueList(List<DownLoadInfo> downLoadInfos, List<CatalogueInfo> catalogueInfos) {

        DownLoadInfo downLoadInfo = null;
        for (CatalogueInfo catalogueInfo : catalogueInfos) {
            if (catalogueInfo != null) {
                String url = catalogueInfo.getDownLoadUrl();
                downLoadInfo = new DownLoadInfo();
                downLoadInfo.setUrl(url);
                downLoadInfo.setChapterId(catalogueInfo.getId());
                downLoadInfo.setChapterName(catalogueInfo.getName());
                downLoadInfo.setHash(catalogueInfo.getHash());
                downLoadInfo.setSavePath(FileUtil.getSavePathByUrl(CatalogNewActivity.this, url));

                //新旧包结构区分
                downLoadInfo.setType(catalogueInfo.getType());

                String fileSize = catalogueInfo.getFileSize();
                if (!TextUtils.isEmpty(fileSize) && fileSize.contains(" ")) {
                    downLoadInfo.setSize(fileSize.split(" ")[0]);
                }
                downLoadInfo.setIsFree(mInfo.getIsFree());
                downLoadInfos.add(downLoadInfo);
                if (catalogueInfo.getChildren() != null && catalogueInfo.getChildren().size() != 0) {
                    parseCatalogueList(downLoadInfos, catalogueInfo.getChildren());
                }
            }
        }
    }


    /**
     * 解析从网络获取的章节信息并填充列表
     *
     * @param catalogueInfos
     */
    private List<DownLoadInfo> fillList(List<CatalogueInfo> catalogueInfos) {
        List<DownLoadInfo> downLoadInfos = new ArrayList<DownLoadInfo>();
        List<DownLoadInfo> tempList = new ArrayList<DownLoadInfo>();


        parseCatalogueList(downLoadInfos, catalogueInfos);


        out:
        for (DownLoadInfo info : downLoadInfos) {
            if (info == null) {
                continue;
            }

            // 一本书有可能新包就包混合，必须每个章节判断是否是新资源

            for (DownLoadInfo downLoadInfo : mDownLoadInfos) {
                // 书的章节结构没有变化的
                if (downLoadInfo != null && downLoadInfo.getChapterId() != null && downLoadInfo.getChapterId().equals(info.getChapterId()) && downLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_OLD) {
                    downLoadInfo.setChapterName(info.getChapterName());
                    downLoadInfo.setUrl(info.getUrl());
                    downLoadInfo.setSavePath(info.getSavePath());
                    downLoadInfo.setSize(info.getSize());
                    downLoadInfo.setIsFree(mInfo.getIsFree());
                    downLoadInfo.setIsKaoShi(mInfo.getRequired());
                    tempList.add(downLoadInfo);
                    DownLoadDB.insertDetail(downLoadInfo);
                    continue out;
                }
            }

            if (info.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_OLD) {
                // 新增章节插入
                DownLoadInfo newDownLoadInfo = new DownLoadInfo();
                newDownLoadInfo.setBookId(mBookId);
                newDownLoadInfo.setBookName(mInfo.getProductName());
                newDownLoadInfo.setIconUrl(mInfo.getCover());
                newDownLoadInfo.setChapterId(info.getChapterId());
                newDownLoadInfo.setChapterName(info.getChapterName());
                newDownLoadInfo.setUrl(info.getUrl());
                newDownLoadInfo.setSavePath(info.getSavePath());
                newDownLoadInfo.setStatus(DownloadStatus.STATUS_NORMAL);
                newDownLoadInfo.setSize(info.getSize());
                newDownLoadInfo.setIsFree(mInfo.getIsFree());
                newDownLoadInfo.setIsKaoShi(mInfo.getRequired());
                newDownLoadInfo.setResourceName(info.getResourceName());
                newDownLoadInfo.setResourceType(info.getResourceType());

                tempList.add(newDownLoadInfo);
                DownLoadDB.insertDetail(newDownLoadInfo);
            }

        }


        return tempList;
    }


    private class ViewPageTest extends StaticPagerAdapter {

        private List<String> titleChar;
        private List<DownLoadInfo> downLoadInfo_lists;

        public ViewPageTest(List<String> tTitleChar, List<DownLoadInfo> downLoadInfo_lists) {
            if (tTitleChar == null) {
                tTitleChar = new ArrayList<String>();
            }
            this.titleChar = tTitleChar;
            this.downLoadInfo_lists = downLoadInfo_lists;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return this.titleChar.get(position);
        }

        @Override
        public int getCount() {
            return this.titleChar.size();
        }

        @Override
        public View getView(ViewGroup container, int position) {
            View mianView = mInflater.inflate(R.layout.catalog_page, null);
            final LayersView layersView = (LayersView) mianView.findViewById(R.id.layear_layout);
            View sortView = mianView.findViewById(R.id.scor_item);

            contentLayersView = layersView;
            ((TextView) mianView.findViewById(R.id.tv_updated)).setText("已更新" + catelogBean.getPublished() + "个章节");
            ((TextView) mianView.findViewById(R.id.count_id)).setText("/共" + catelogBean.getPeriods() + "个章节");
            layersView.setForm(fromResource);
            layersView.setKaoShi(mInfo.getRequired());
            layersView.setmDownLoadInfoList(downLoadInfo_lists);
            layersView.setBookchapters(bookchapters);
            layersView.setCatalogueInfos(mCatalogueInfos);


            sortView.setVisibility(View.VISIBLE);
            final ImageView sortImage = (ImageView) mianView.findViewById(R.id.sort_iocn);

            if (catelogBean.getIsdesc() == 1) {
                //降序
                debug("降序");
                sortImage.setImageResource(R.mipmap.sort_rev);
                layersView.setSortState(true);
            } else {
                debug("升序");
                sortImage.setImageResource(R.mipmap.sort_def);
                layersView.setSortState(false);
            }

            mianView.findViewById(R.id.sco_lin).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (layersView.sort()) {
                        sortImage.setImageResource(R.mipmap.sort_rev);
                    } else {
                        sortImage.setImageResource(R.mipmap.sort_def);
                    }
                }
            });
//                        checkValid(layersView,EApplication.BRAND_ID + "", mServiceId + "", mBookId,null, null, null);
            handleCatalogClick(layersView);
            return mianView;
        }

    }

    /**
     * 处理目录的点击事件
     *
     * @param layersView
     */

    private void handleCatalogClick(LayersView layersView) {


        layersView.setOnItemClickListener(new LayersViewItemClickListener() {
            @Override
            public void avertRepeatOnClick(Node node, View view) {
                //点击章节
                if (node.isSuo() && fromResource != IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs) {
                    ToastUtil.INSTANCE.toastInCenter(CatalogNewActivity.this, "考试用书不支持自主学习哦~~");
                } else if (fromResource == IntentValue.JumpToBookCatalogType.FROM_BUY_SERVICE_BOOKs) {
                    ToastUtil.INSTANCE.toastInCenter(CatalogNewActivity.this, "请到首页中查看书籍内容~~");
                    return;
                } else {
                    Hoder hoder = new Hoder();
                    hoder.imageView = (ImageView) view.findViewById(R.id.item_iocn);
                    executorDBThread(node.getCatalogueInfo(), hoder);
//                    showGetPermissDialog(node.getCatalogueInfo(), hoder);
                }
            }

            @Override
            public boolean freeForLearnContralItemClick(int item, Node node, Node node0) {
                //对非第一个一级条目 父条目判断
                    /*if (node.getpId() == 0 && item != 0) {
                        ToastUtil.INSTANCE.toastInCenter(CatalogNewActivity.this, " 普通 这个条目不是第一个根节点");
                        return false;
                    }
                    //对第一个条目 父条目判断
                    if (node.getpId() == 0 && item == 0) {
                        ToastUtil.INSTANCE.toastInCenter(CatalogNewActivity.this, "普通  这个条目被控制 第一个父节点");
                        return true;
                    }
                    //对第一个父条目 下 子二级目录判断
                    if (node.getpId() != 0 && node.getpId() == node0.getId()) {
                        ToastUtil.INSTANCE.toastInCenter(CatalogNewActivity.this, "普通  这个条目被控制 子节点");
                        return true;
                    }
                    //对第一个父条目 下 子三级目录判断
                    if (node.getpId() != 0 && node.getParent() != null && node.getParent().getpId() == node0.getId()) {
                        ToastUtil.INSTANCE.toastInCenter(CatalogNewActivity.this, "普通 这个条目被控制 子 子节点");
                        return true;
                    }
                    ToastUtil.INSTANCE.toastInCenter(CatalogNewActivity.this, "普通 这个是非第一个一级条目 最后");
                    return false;*/
                return true;

            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back_img) {
            this.finish();
        } else if (id == R.id.tv_add_to_bookdesk) {
            if (DoubleClickCheckUtils.vertifyDuration()) {
                showCricleProgress();
                UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
                EpaperDao.getInstance().setHeadLastBooks(mBookId, mServiceId, (int) userInfoBase.getUserId(), currentActionOfAddBookButton, new BaseExtCallBack(CatalogNewActivity.this) {
                    @Override
                    public void success(Object data) {
                        hideCricleProgress();
                        sendBroadcast(new Intent(EpaperConstant.BROADCAST_SETBOOKS_HEAD));
                        if (currentActionOfAddBookButton == ACTION_REOMVEBOOK_TO_BOOKDESK) {
                            ToastUtil.INSTANCE.toastCenterSuccess("已从书桌移除");
                            currentActionOfAddBookButton = ACTION_ADD_BOOK_TO_BOOKDESK;
                        } else {
                            ToastUtil.INSTANCE.toastCenterSuccess("已添加到书桌");
                            currentActionOfAddBookButton = ACTION_REOMVEBOOK_TO_BOOKDESK;
                        }
                        //setAddBookTextViewText();
                    }

                    @Override
                    public void failed(Object data) {
                        hideCricleProgress();
                        super.failed(data);
                        if (currentActionOfAddBookButton == ACTION_REOMVEBOOK_TO_BOOKDESK) {
                            ToastUtil.INSTANCE.toastCenterError("移除失败，请稍后重试");
                        } else {
                            ToastUtil.INSTANCE.toastCenterError("添加失败，请稍后重试");
                        }

                    }

                    @Override
                    public void failed(int errorCode, Object data) {
                        hideCricleProgress();
                        super.failed(errorCode, data);
                        if (currentActionOfAddBookButton == ACTION_REOMVEBOOK_TO_BOOKDESK) {
                            ToastUtil.INSTANCE.toastCenterErrorWithErrorCode("移除失败，请稍后重试", errorCode);
                        } else {
                            ToastUtil.INSTANCE.toastCenterErrorWithErrorCode("添加失败，请稍后重试", errorCode);
                        }
                    }

                });
            }
        }
    }


    private void debug(String message) {
        Log.d(this.getClass().getName(), message);
    }


    @Override
    protected void onResume() {
        if (!EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().register(this);
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (EventBus.getDownLoadInstance().isRegistered(this) && !isTopActivity()) {
            EventBus.getDownLoadInstance().unregister(this);
            hideDownloadProgress();
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDownLoadInstance().isRegistered(this)) {
            EventBus.getDownLoadInstance().unregister(this);
        }
        super.onDestroy();
    }


    private void dealCircleProgress(final DownLoadInfo downLoadInfo, Hoder hoder) {
        if (hoder == null)
            return;

        switch (downLoadInfo.getStatus()) {
            case DownloadStatus.STATUS_FILE_DOWNLOAD:
                hideCancelButtonOfDownloadProgress();
                hideDownloadHorizontalProgressBar();
                break;
            case DownloadStatus.STATUS_COMPLETED:
                hideDownloadProgress();
                String packageDir = ESystem.getPackagesCatalogue(mCurrentDownloadInfo.getBookId(), mCurrentDownloadInfo.getChapterId());
                //判断解压后文件是否存在，不存在的话直接给出加载失败提示
                if (new File(packageDir).exists()) {
                    if (mCurrentCatalogueInfo != null && mCurrentHolder != null) {
                        doClickListener(mCurrentCatalogueInfo, mCurrentDownloadInfo, mCurrentHolder, false);
                    }
                } else {
                    ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                }

                break;
            case DownloadStatus.STATUS_FAILED:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_SDISFULL:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_sdfull_and_retry);
                break;
            case DownloadStatus.STATUS_FAILED_UNZIP:
                hideDownloadProgress();
                ToastUtil.INSTANCE.toastCenterError(R.string.load_failed_unzip_and_retry);
                break;
            case DownloadStatus.STATUS_DOWNLOADING:
                if (HomeWorkUtil.isDownloadInfoTheSameToClickDownLoadInfo(downLoadInfo, mCurrentClickDownloadInfo)) {
                    updateDownloadProgress(downLoadInfo.getProgress());
                }
                break;
        }
    }

    public static class Hoder {
        public ImageView imageView;
    }

    /**
     * 用于监听pageview
     *
     * @param position
     */
    public void onPageSelected(int position) {
        //显示的
        //        if (mViewPageTitleXiFu.getVisibility() == View.VISIBLE) {
        //            mScrollView.scrollTo(0, (int) (page_titles.getY() - page_titles.getHeight()));
        //        }
    }

    /**
     * 添加书籍到书柜记录(上传到服务器)
     */
    public void setBookcaseToServer() {

        EpaperDao.getInstance().setBookcaseToServer(EApplication.BRAND_ID, mBookId, mInfo.getServer().getId(), new BaseExtCallBack(CatalogNewActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                CWLog.i("TAT", "【CatalogActivity】 上传书柜记录 failed！");
                //                showToastError(R.string.connect_disable);

                DialogUtil.showFailedToastByErrorType(CatalogNewActivity.this, data);

            }

            @Override
            public void failed(Object data) {
                super.failed(data);
                CWLog.i("TAT", "【CatalogActivity】 上传书柜记录 failed！");
                //                showToastError(R.string.connect_disable);
                DialogUtil.showFailedToastByErrorType(CatalogNewActivity.this, data);
            }

            @Override
            public void success(Object data) {
                CWLog.i("TAT", "【CatalogActivity】 上传书柜记录 success！");
                mInfo.setAdded(true);
                mInfo.isBookCase = 1;
                //Intent intent = new Intent();
                //                intent.putExtra(BaseIntentFlag.INTENT_FLAG_OBJ, mInfo);
                //                setResult(RESULT_OK, intent);
                //                finish();
                showSuccessDialog(mInfo);


            }
        });
    }

    /**
     * 添加书籍成功
     */
    public void showSuccessDialog(final EpaperInfo epaperInfo) {
        String bookName = epaperInfo.getProductName();
        try {
            if (!isFinishing()) {
                CWDialog dialog = new CWDialog(CatalogNewActivity.this, false, false).setMessage(getString(R.string.add_book_success, bookName), 16, Color.BLACK)
                        //“去书桌学习”按钮，跳转到书桌
                        .setNegativeButton(R.string.go_to_book_desk, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent();
                                intent.putExtra(BaseIntentFlag.INTENT_FLAG_OBJ, epaperInfo);
                                intent.putExtra(CLOSE_ADDBOOKACTIVITY, true);
                                setResult(RESULT_OK, intent);
                                finish();

                            }
                        })
                        //“继续添加”按钮，返回书柜页面
                        .setPositiveButton(R.string.continue_here, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent();
                                intent.putExtra(BaseIntentFlag.INTENT_FLAG_OBJ, epaperInfo);
                                intent.putExtra(CLOSE_ADDBOOKACTIVITY, false);
                                setResult(RESULT_OK, intent);
                                finish();
                            }
                        });
                dialog.show();
            }
        } catch (WindowManager.BadTokenException e) {
            e.getStackTrace();
        }


    }

    /**
     * 添加书籍失败
     */
    public void showErrorDialog() {
        CWDialog dialog = new CWDialog(CatalogNewActivity.this, false, false).setMessage(getString(R.string.error_add_book), 16, Color.BLACK).setPositiveButton("确定", null, true, getResources().getDrawable(R.drawable.dialog_floor_selector));
        dialog.show();

    }


    /**
     * 得到当前网速
     *
     * @return
     */
    private long getNetSpeed() {
        long traffic_data = TrafficStats.getTotalRxBytes() - total_data;
        total_data = TrafficStats.getTotalRxBytes();
        return traffic_data / 1024;
    }

    /**
     * 获取时间
     *
     * @return
     */
    private String getMil(int mil) {
        int sco = mil / 60;
        int miao = mil % 60;
        String fenz;
        if (sco < 10) {
            fenz = "0" + sco;
        } else if (sco > 59) {
            return "59:59";
        } else {
            fenz = sco + "";
        }
        String miaoZ;
        if (miao < 10) {
            miaoZ = "0" + miao;
        } else {
            miaoZ = miao + "";
        }
        return fenz + ":" + miaoZ;
    }


    private DownLoadInfo mCurrentDownloadInfo = new DownLoadInfo();
    private DownLoadInfo mCurrentClickDownloadInfo;
    private CatalogueInfo mCurrentCatalogueInfo;
    private Hoder mCurrentHolder;

    public void showDownloadDialog(DownLoadInfo downLoadInfo, CatalogueInfo catalogueInfo, Hoder hoder) {
        mCurrentCatalogueInfo = catalogueInfo;
        mCurrentHolder = hoder;
        showDownloadProgress();
        showCancelButtonOfDownloadProgress();
    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog(final CatalogueInfo catalogueInfo, final Hoder hoder) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss(catalogueInfo, hoder);
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss(catalogueInfo, hoder);
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private void checkSDcardpermiss(final CatalogueInfo catalogueInfo, final Hoder hoder) {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读写本地存储权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                executorDBThread(catalogueInfo, hoder);
                            }
                        }
                    });
        } else {
            executorDBThread(catalogueInfo, hoder);
        }
    }

    /**
     * 未完成作业提交提醒窗口
     */
    public void showConfirmCommitDialog(final Activity context, final String tips) {
        CWDialog dialog = new CWDialog(context);
        dialog.setMessage(tips);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();

                            }
                        })
                .show();
    }
}
